package models;

import play.*;
import play.data.validation.Required;
import play.data.validation.Valid;
import siena.Model;
import siena.Query;
import java.util.*;
import siena.Id;
import siena.embed.Embedded;
import siena.embed.Embedded.Mode;
import javax.xml.bind.annotation.*;
import com.google.appengine.api.NamespaceManager;
import siena.core.lifecycle.PostInsert;
import models.Profile.ProfileType;

public class Subscriber extends BaseModel {

	@Required
	public String name;
	
	@Embedded(mode=Mode.NATIVE)
	@Valid
	@Required
	public ContactInformation contact_information;
	
	@Valid
	@Embedded(mode=Mode.NATIVE) 
	public BillingInformation billing_information;
	
	
	public static Query<Subscriber> all() {
		return all(Subscriber.class);
	}
	
	
	public static Subscriber findByName(String name) {
		return all().filter("name", name).get();
	}
	
	public static int count() {
		return all().count();
	}
		
	public static List<Subscriber>findAll() {
		return all().fetch();
	}
	
	public static List<Subscriber> paginate(Query<Subscriber> query, int offset, int limit) {
		return query.fetch(limit, offset);
	}
	
	
	public static Subscriber get(long id) {
        return all().filter("id", id).get();
	}
	
	@PostInsert
	public  void upInfrastructure() {
		String oldNamespace = NamespaceManager.get();
		NamespaceManager.set(this.name);
		Profile profile = new Profile(ProfileType.ADMIN);
		profile.insert();
		profile = new Profile(ProfileType.FAMILIAR);
		profile.insert();
		profile = new Profile(ProfileType.INTERNSHIP);
		profile.insert();
		Residence residence = new Residence();
		residence.name = this.name;
		residence.descriptionName = "Nombre descriptivo (" + this.name + ")";
		residence.insert();
		User admin = new User();
		admin.username = "admin";
		admin.password = "admin";
		admin.basic_information = new BasicInformation();
		admin.basic_information.firstName = "Administrador";
		admin.basic_information.lastName = this.name;
		admin.insert();
		UserProfile user_profile = new UserProfile(admin,
				Profile.findByType(Profile.ProfileType.ADMIN));
		user_profile.insert();
		admin =  User.findByUsername("admin");
		NamespaceManager.set(oldNamespace);
	}
	
}